import { useState, useEffect } from 'react';
import style from './index.module.scss';
import ChangeRecord from './change-record';
import Record from './record';
import Rule from './rule';
import Gift from './gift';
import cat from '@/assets/images/cats-eat-fish/cat.png';
import fish from '@/assets/images/cats-eat-fish/fish.png';
import catEatFish from '@/assets/images/cats-eat-fish/cat-eat-fish.png';
import red from '@/assets/images/cats-eat-fish/red.png';
import blue from '@/assets/images/cats-eat-fish/blue.png';
import giftDiamond from '@/assets/images/cats-eat-fish/gift-diamond.png';
import { Checkbox, Stepper, Dialog } from 'react-vant';
import { Toast } from 'react-vant';
import classNames from 'classnames';

const BaseUrl =
    process.env.REACT_APP_ENV === 'prod'
        ? 'https://webapi.pupupal.com'
        : 'https://kk-test-webapi.sayhaiapp.com';
const urlParams = new URLSearchParams(window.location.search);
const authorizationToken = urlParams.get('userId');
const messages = [
    {
        content: '喵喵吃饱了，<br />就有机会开出招财猫礼物哦～',
        className: classNames(style.barrage, style.barrage1),
    },
    {
        content: '每次送小鱼干均有机会瓜分聚宝盆的钻石哦~',
        className: classNames(style.barrage, style.barrage2),
    },
    {
        content: '出招财猫礼物啦,<br />聚宝盆会增加58钻石哦~',
        className: classNames(style.barrage, style.barrage3),
    },
];

let timer = null;

const Index = () => {
    const [showPage, setShowPage] = useState(0);
    const [checked, setChecked] = useState(false);
    const [value, setValue] = useState(10);
    const [info, setInfo] = useState({});
    const [progress, setProgress] = useState(0);
    const [isFeeding, setIsFeeding] = useState(false); // 调取投喂接口中
    const [isAutoFedding, setIsAutoFedding] = useState(false); // 正在自动投喂
    const [diamond, setDiamond] = useState();
    const [currentIndex, setCurrentIndex] = useState(0); // 气泡index
    const [isShowing, setIsShowing] = useState(true);

    const [fishBarrageIndex, setFishBarrageIndex] = useState(0); // 投喂小鱼弹幕
    const [giftInfo, seGiftInfo] = useState({}); // 瓜分钻石弹窗信息
    const [visible, setVisible] = useState(true); // 瓜分钻石弹窗信息

    const clickFeeding = () => {
        if (checked) {
            setIsAutoFedding(true);
            timer = setInterval(() => {
                feeding();
            }, 1500);
        } else {
            feeding();
        }
    };
    const clickStop = () => {
        if (timer) {
            clearInterval(timer);
            timer = null; // 清除后将 timer 置为 null
        }
        setIsAutoFedding(false);
    };
    // 投喂
    const feeding = async () => {
        setIsFeeding(true);
        let url = `/raffle/luckyCat/feeding`;
        fetch(BaseUrl + url, {
            method: 'POST',
            headers: {
                Authorization: authorizationToken,
                'content-type': 'application/json',
            },
            body: JSON.stringify({
                number: value,
                // userId: info.userId,
            }),
        })
            .then((response) => response.json())
            .then((response) => {
                setTimeout(() => {
                    setIsFeeding(false);
                }, 1000);
                if (response.code === 200 && response.data) {
                    if (response.data?.divideStarCoin > 0) {
                        // 瓜分钻石
                        Dialog.show({
                            visible: visible,
                            width: '100%',
                            showConfirmButton: false,
                            closeable: true,
                            closeIcon: <div className={style.close}></div>,
                            closeOnClickOverlay: true,
                            message: (
                                <div className={style.messageBox1}>
                                    <div className={style.giftContent}>
                                        {/* <p className={style.p1}></p> */}
                                        <img
                                            className={style.gift}
                                            src={giftDiamond}
                                        />
                                        <div className={style.p2}>
                                            <p>恭喜你获得瓜分钻石的机会</p>
                                            <p>
                                                并成功瓜分
                                                {response.data?.divideStarCoin}
                                                蓝钻
                                            </p>
                                        </div>
                                        <div
                                            className={style.btn}
                                            onClick={() => setVisible(false)}
                                        ></div>
                                    </div>
                                </div>
                            ),
                        });
                    }
                    getProgress();
                    getDiamond();
                } else {
                    Toast.info(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };
    const getProgress = async () => {
        let url = `/raffle/luckyCat/queryProgress`;
        fetch(BaseUrl + url, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    setInfo(response.data);
                } else {
                    if (checked) {
                        clickStop();
                    }
                    Toast.info(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const getDiamond = async () => {
        let url = `/asset/account/balance`;
        fetch(BaseUrl + url, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    setDiamond(response.data);
                } else {
                    Toast.info(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    useEffect(() => {
        if (authorizationToken) {
            getProgress();
            getDiamond();
        } else {
            console.error('Authorization token not found in URL');
        }
    }, []);

    useEffect(() => {
        if (info) {
            const currentProgress = info.luckCatCurrentProgress || 0;
            const overallProgress = info.luckCatOverallProgress || 1000;
            const progressPercentage =
                (currentProgress / overallProgress) * 100;
            setProgress(progressPercentage);
        }
    }, [info]);

    useEffect(() => {
        let showTimeout;
        let switchInterval;

        if (isShowing) {
            // 设置10秒后隐藏当前消息
            showTimeout = setTimeout(() => {
                setIsShowing(false);
            }, 10000);
        } else {
            // 设置60秒后显示下一个消息
            switchInterval = setInterval(() => {
                setCurrentIndex(
                    (prevIndex) => (prevIndex + 1) % messages.length
                );
                setIsShowing(true);
            }, 60000);
        }

        // 清理定时器
        return () => {
            clearTimeout(showTimeout);
            clearInterval(switchInterval);
        };
    }, [isShowing, currentIndex]);

    useEffect(() => {
        if (isFeeding) {
            setFishBarrageIndex((prevIndex) => (prevIndex + 1) % 2);
        }
    }, [isFeeding]);

    return (
        <>
            {
                <div className={style.container}>
                    <div
                        className={`${style.btn} ${style.btn1}`}
                        onClick={() => setShowPage(2)}
                    ></div>
                    <div
                        className={`${style.btn} ${style.btn2}`}
                        onClick={() => setShowPage(1)}
                    ></div>
                    <div
                        className={style.changeRecord}
                        onClick={() => setShowPage(3)}
                    ></div>
                    <div
                        className={style.bubble}
                        onClick={() => setShowPage(3)}
                    >
                        <div className={style.bubble_img}></div>
                        <div className={style.bubble_text}>
                            已收集{info?.luckCatPondBricks}钻石
                        </div>
                    </div>
                    <div className={style.title}></div>
                    <div className={style.barrageBox}>
                        {!isFeeding && (
                            <div
                                dangerouslySetInnerHTML={{
                                    __html: isShowing
                                        ? messages[currentIndex].content
                                        : '',
                                }}
                                className={
                                    isShowing
                                        ? messages[currentIndex].className
                                        : ''
                                }
                            />
                        )}
                        {isFeeding && (
                            <div>
                                {fishBarrageIndex === 0 && (
                                    <div
                                        className={classNames(
                                            style.barrageFish,
                                            style.barrage4
                                        )}
                                    >
                                        我投喂了{value}条小鱼干
                                        <img src={fish} alt="" />
                                    </div>
                                )}
                                {fishBarrageIndex === 1 && (
                                    <div
                                        className={classNames(
                                            style.barrageFish,
                                            style.barrage5
                                        )}
                                    >
                                        我投喂了{value}条小鱼干
                                        <img src={fish} alt="" />
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                    <div className={style.cat}>
                        <img src={isFeeding ? catEatFish : cat} alt="" />
                    </div>
                    <div className={style.bottomBox}>
                        <div className={style.progress}>
                            <div
                                className={style.progress_bar}
                                style={{ width: `${progress}%` }}
                            ></div>
                            <div className={style.progress_text}>
                                当前饱和度{info?.luckCatCurrentProgress || 0}/
                                {info?.luckCatOverallProgress || 1000}
                            </div>
                        </div>
                        <div className={style.fish}>
                            <div></div>
                            <div></div>
                        </div>
                        <div className={style.autoBox}>
                            <Checkbox
                                className={style.checkbox}
                                checked={checked}
                                shape="square"
                                onChange={setChecked}
                                checkedColor="#E9611B"
                                iconSize="14px"
                            >
                                自动投喂
                            </Checkbox>
                            <div className={style.countBox}>
                                {checked ? '自动' : '单次'}
                                投喂数量
                                <Stepper
                                    className={style.step}
                                    value={value}
                                    onChange={(val) => setValue(val)}
                                    theme="round"
                                    buttonSize="22"
                                    disableInput
                                    min={10}
                                    max={500}
                                    step={10}
                                />
                            </div>
                        </div>
                        {isAutoFedding ? (
                            <div className={style.subBtn} onClick={clickStop}>
                                取消投喂
                            </div>
                        ) : (
                            <div
                                className={classNames(style.subBtn, {
                                    [style.disabled]: isFeeding,
                                })}
                                onClick={clickFeeding}
                            >
                                投喂<span>({value}钻石)</span>
                            </div>
                        )}
                        <div className={style.bottom}>
                            <div className={style.diamond}>
                                <img src={blue} alt="" />
                                蓝钻数量:{diamond?.starCoin}
                            </div>
                            <div className={style.diamond}>
                                <img src={red} alt="" />
                                红钻数量:{diamond?.redDiamond}
                            </div>
                            {/* <div className={style.charge}>{"去充值>>"}</div> */}
                        </div>
                    </div>
                </div>
            }
            {showPage === 1 && <Record clickBack={() => setShowPage(0)} />}
            {showPage === 2 && <Rule clickBack={() => setShowPage(0)} />}
            {showPage === 3 && (
                <ChangeRecord clickBack={() => setShowPage(0)} />
            )}
            <Gift giftInfo={giftInfo} />
        </>
    );
};

export default Index;
